from tool import send, log
import datetime
import time


def get_start():
    try:
        url = "http://127.0.0.1:9990/optdb/file/get"
        cmd = {"p": "setting", "sn": "opt"}

        body = send(url, cmd)
        if "data" not in body:
            return None

        body = body["data"]

        start = int(body["start"])
        keep = int(body["keep"])

        fmt = "%Y%m%d%H:%M:%S"

        now = time.strftime(fmt)
        now = datetime.datetime.strptime(now, fmt)

        diff = datetime.timedelta(seconds=start)
        s = (now + diff).strftime(fmt)

        diff = datetime.timedelta(seconds=start + keep)
        e = (now + diff).strftime(fmt)

        return [s, e]
    except Exception as e:
        log("do start error: %s" % e)

    return []


def do_que(cfg, k, que):
    range = []
    range_val = []

    wsn = cfg["wsn"]

    while True:
        try:
            data = que.get()

            if "gun" in data:
                range = get_start()
                range_val = []
                continue

            send("http://127.0.0.1:9985/plc/put", {"line": "1", "sn": wsn, "v": data})

            if not range:
                range_val = []
                continue

            if len(range) != 2:
                range_val = []
                continue

            fmt = "%Y%m%d%H:%M:%S"
            now = time.strftime(fmt)

            if now < range[0]:
                range_val = []
                continue

            # for test=====
            # log(range)

            if now > range[1]:
                ret = 0

                for d in range_val:
                    ret += d

                ret /= len(range_val)

                val = {"f%s" % k: ret}

                # for test=====
                # log(val)

                send("http://127.0.0.1:9985/plc/put", {"line": "1", "sn": wsn, "v": val})

                range_val = []
                range = []

                continue

            range_val.append(data[k])
        except Exception as e:
            log("do que error: %s" % e)
